extends InputClass

var drag_start_pos := Vector2.ZERO


func _ready() -> void:
	Input.joy_connection_changed.connect(joy_connection_changed)



func on_mouse_click_avatar(index: int) -> void:
	SoundManager.play_ui("Click")
	var k = Game.player_id_map.find_key(index)
	if k == null:
		Game.player_id_map["key_"] = index
		Game.ui.referesh_select_data()




func select_by_dir() -> void:
	var dir_arr := ["left", "right"]
	var old_map: Dictionary = Game.player_id_map.duplicate()
	for key in Game.controller_arr.keys():
		for dir in dir_arr:
			if InputMap.has_action(key + "move_" + dir) and Input.is_action_just_pressed(key + "move_" + dir):
				SoundManager.play_ui("Pluck")
				var new_value: int = 0
				var exist_value: Array = Game.player_id_map.values()
				if Game.player_id_map.has(key):
					new_value = Game.player_id_map[key]
					Game.player_id_map.erase(key)
					
				for i in Game.player_data.size():
					new_value = (new_value + 1) if dir == "right" else (new_value - 1)
					if new_value >= Game.player_data.size():
						new_value = 0
					elif new_value < 0:
						new_value = Game.player_data.size() - 1
					
					if not new_value in exist_value:
						Game.player_id_map[key] = new_value
						break
				
	if old_map != Game.player_id_map:
		Game.ui.referesh_select_data()
		

func control_player(_delta: float) -> void:
	for p: Player in Game.players:
		if just_pressed(p.device, "jump"):
			p.jump_timer.start()


func _process(delta: float) -> void:
	if Input.is_action_just_pressed("ui_up") or Input.is_action_just_pressed("ui_down"):
		SoundManager.play_ui("Select")
		
		
	match Game.current_state:
		Game.GameState.HOME:
			pass
		Game.GameState.GAMING:
			if Input.is_action_just_pressed("game_pause"):
				Game.pause_game(false if Game.is_game_pause else true)
			control_player(delta)
		Game.GameState.SELECT_CHARACTOR:
			select_by_dir()
		Game.GameState.MENU:
			if Input.is_action_just_pressed("game_pause"):
				Game.pause_game(false if Game.is_game_pause else true)
		Game.GameState.GAME_OVER:
			pass


func _unhandled_input(event: InputEvent) -> void:
	store_button_event(event) #必须最先执行
	handle_touch(event)




## 处理触摸屏
func handle_touch(e: InputEvent) -> void:
	if e is InputEventScreenTouch: 
		var touch := e as InputEventScreenTouch
		if touch.pressed:
			if Game.is_gaming(): Game.players[0].jump_timer.start()
			drag_start_pos = touch.position
		else:
			if drag_start_pos.length():
				if touch.position.distance_to(drag_start_pos) > 20 and drag_start_pos.direction_to(touch.position).y < 0:
					Game.pause_game(true)
				elif touch.position.distance_to(drag_start_pos) > 20 and drag_start_pos.direction_to(touch.position).y > 0:
					Game.pause_game(false)
	elif e is InputEventScreenDrag:
		pass









